package com.wing.user.controller.admin;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.user.model.entity.Authority;
import com.wing.user.model.entity.Menu;
import com.wing.user.model.response.MenuVO;
import com.wing.user.service.AuthorityService;
import com.wing.user.service.MenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 */
@Api(value = "Admin-菜单管理", tags = "#/user/menu")
@RestController
@RequestMapping("/user/admin/menu")
@RequiredArgsConstructor
public class MenuController {

    private final MenuService menuService;
    private final AuthorityService authorityService;

    @ApiOperation(value = "查询所有菜单", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "搜索关键字", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<Menu> list(String keyword) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        //搜索
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like("name", keyword);
        }
        queryWrapper.orderBy(true, false, "sort_number");
        List<Menu> list = menuService.list(queryWrapper);
        return new PageResult<>(list);
    }

    @ApiOperation(value = "查询菜单树", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyword", value = "搜索关键字", dataType = "String", paramType = "query")
    })
    @GetMapping("/tree")
    public JsonResult tree() {
        List<Menu> list = menuService.list(new QueryWrapper<Menu>().orderBy(true, true, "sort_number"));
        return JsonResult.success(getMenuTree(list, -1L));
    }

    @ApiOperation(value = "添加菜单", notes = "添加")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "form")
    })
    @PostMapping("/add")
    public JsonResult add(Menu menu) {
        menuService.setValue(menu);
        if (menuService.save(menu)) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "修改菜单", notes = "修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access_token", value = "令牌", required = true, dataType = "String", paramType = "form")
    })
    @PutMapping("/update")
    public JsonResult update(Menu menu) {
        menuService.setValue(menu);
        if (menuService.updateById(menu)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "删除菜单", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "menuId", value = "菜单id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long menuId) {
        menuService.delete(menuId);
        return JsonResult.success("删除成功");
    }

    @ApiOperation(value = "查询所有权限", notes = "搜索")
    @GetMapping("/pageUrlList")
    public JsonResult pageUrlList() {
//        List<Authority> authorityList = authorityService.list(new QueryWrapper<Authority>().likeLeft("authority", "/list").groupBy("page_url"));
        List<Authority> authorityList = authorityService.list(new QueryWrapper<Authority>().likeLeft("authority", "/list").or().likeLeft("authority","/list2"));
        return JsonResult.success(authorityList);
    }

    /**
     * 递归转化树形菜单
     */
    private List<Map<String, Object>> getMenuTree(List<Menu> menus, Long parentId) {
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 0; i < menus.size(); i++) {
            Menu temp = menus.get(i);
            if (parentId.intValue() == temp.getParentId().intValue()) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", temp.getName());
                map.put("value", temp.getId());
                map.put("icon", temp.getIcon());
                map.put("url", StrUtil.isBlank(temp.getUrl()) ? "javascript:;" : temp.getUrl());
                map.put("children", getMenuTree(menus, menus.get(i).getId()));
                list.add(map);
            }
        }
        return list;
    }

    @ApiOperation(value = "获取所有一级菜单", notes = "查询")
    @GetMapping("/getAllParentMenu")
    public JsonResult getAllParentMenu() {
        List<Menu> list = menuService.list(new QueryWrapper<Menu>()
                .eq("parent_id",-1l)
                .orderBy(true, true, "sort_number"));
        return JsonResult.success(list);
    }

    @ApiOperation(value = "根据父id查询所有子级", notes = "查询")
    @GetMapping("/getMenuByParentId")
    public JsonResult getMenuByParentId() {
        List<Menu> list = menuService.list(new QueryWrapper<Menu>()
                .orderBy(true, true, "sort_number"));
        return JsonResult.success(list);
    }

    /**
     * 根据id查询菜单信息
     */
    @GetMapping("/getMenuInfo")
    public JsonResult<MenuVO> getMenuById(@RequestParam("id")Long id){
        return JsonResult.success(menuService.getById(id));
    }

}
